package com.cwf.framework.aspectj;

import com.alibaba.fastjson2.JSON;
import com.cwf.framework.aspectj.annotation.MyPage;
import com.cwf.framework.page.entity.PageParams;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class PageAop {

    @Resource
    private HttpServletRequest req;

    private String page;

    private String size;


    @Pointcut("@annotation(com.cwf.framework.aspectj.annotation.MyPage)")
    public void doPointcut() {

    }

    @Around("@annotation(myPage)")
    public Object test(ProceedingJoinPoint point,MyPage myPage) throws Throwable {


        if (req.getMethod().equals("POST")){
            PageParams params = new PageParams();
            for (Object arg : point.getArgs()){
                params = JSON.parseObject(JSON.toJSONString(arg), PageParams.class);
            }

            page = params.getPage();
            size=params.getSize();
            System.out.println(params);
            log.info("post请求");
        }else {
            page = req.getParameter("page");
            size = req.getParameter("size");
        }


        if (!StringUtils.hasLength(page)) {
            page = myPage.page()+"";
        }

        if (!StringUtils.hasLength(size)) {
            size = myPage.size()+"";
        }

        if (!StringUtils.hasLength(page) && !StringUtils.hasLength(size)) {
            page = myPage.page()+"";
            size = myPage.size()+"";
        }

        PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(size));

        return point.proceed();
    }

    @After("doPointcut()")
    public void after() {
        log.info("\npage: {} size: {}", page, size);
        log.info("清除分页线程");
        PageHelper.clearPage();
    }


    private String inputStreamToString(InputStream is) {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        String str = "";
        try {
            while ((length = is.read( buffer )) != -1) {
                result.write( buffer, 0, length );
            }
            str = result.toString( StandardCharsets.UTF_8.name() );
            return str;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }


}
